package com.bj58.ecdata.webframework;

import java.io.File;
import java.net.URL;
import java.util.EnumSet;

import javax.servlet.DispatcherType;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.NCSARequestLog;
import org.eclipse.jetty.server.RequestLog;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ThreadPool;
import org.eclipse.jetty.webapp.JettyWebXmlConfiguration;
import org.eclipse.jetty.webapp.WebAppContext;

import com.bj58.argo.servlet.ArgoFilter;

public abstract class AbstractServer {

	protected Server server;
	protected final Config config = new Config();

	public AbstractServer(String[] args) {

	}

	public abstract void init(Config config, String[] args);

	public void run(String[] anArgs) throws Exception {
		init(config, anArgs);
		start();
		join();
	}

	public void start() throws Exception {
		server = new Server();
		System.setProperty("DEBUT", "ture");
//		server.setThreadPool(createThreadPool());
		//这是http的连接器
		ServerConnector connector = new ServerConnector(server);
		connector.setPort(config.port);
		server.addConnector(connector);
		server.setHandler(createHandlers());
		server.setStopAtShutdown(true);
		server.start();
	}

	public void join() throws InterruptedException {
		server.join();
	}

	public void stop() throws Exception {
		server.stop();
	}

	public ThreadPool createThreadPool() {
		// TODO: You should configure these appropriately
		// for your environment - this is an example only
		QueuedThreadPool _threadPool = new QueuedThreadPool();
		_threadPool.setMinThreads(config.min_thread);
		_threadPool.setMaxThreads(config.max_thread);
		return _threadPool;
	}

	private Handler createHandlers() {

		WebAppContext _ctx = new WebAppContext();
		
		// enable web 3.0 annotations
        org.eclipse.jetty.webapp.Configuration.ClassList classlist = org.eclipse.jetty.webapp.Configuration.ClassList.setServerDefault(server);
        classlist.addBefore(JettyWebXmlConfiguration.class.getName(), AnnotationConfiguration.class.getName());
//		_ctx.setConfigurations(new Configuration[] {
//				new AnnotationConfiguration(),
//				 new WebInfConfiguration(),
//				new WebXmlConfiguration(), new FragmentConfiguration(),
//				new EnvConfiguration(), new PlusConfiguration(),
//				new JettyWebXmlConfiguration() });
        _ctx.addFilter(ArgoFilter.class, "/*", EnumSet.<DispatcherType>of(DispatcherType.REQUEST));
		String tempDirPath = config.getTempDir();

		if (tempDirPath == null)
			tempDirPath = "/data/jetty/";
		if (!tempDirPath.endsWith("/"))
			tempDirPath = tempDirPath + "/";

		tempDirPath = tempDirPath + this.getClass().getSimpleName() + "/" + config.projectName + "/";

		System.setProperty("jetty.home", tempDirPath);
		File tempDir = new File(tempDirPath);
		if (!tempDir.exists()) {
			tempDir.mkdirs();
		}
		_ctx.setTempDirectory(tempDir);

		_ctx.setContextPath(config.contextPath);
		_ctx.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");

		if (isRunningInShadedJar()) {
			_ctx.setWar(getShadedWarUrl());
			// _ctx2.setWar(getShadedWarUrl());
		} else {
			_ctx.setWar(config.webapp);
			// _ctx2.setWar(PROJECT_RELATIVE_PATH_TO_WEBAPP);
		}
//		_ctx.setDescriptor(config.web_xml);         //指定web.xml文件，可选
//		_ctx.setResourceBase(getShadedWarUrl());     //设置项目资源路径
//		HandlerList _contexts = new HandlerList();
//		_contexts.setHandlers(new Handler[]{_ctx});
//
//		HandlerCollection _result = new HandlerCollection();
//		if (config.log) {
//			// 如果是测试服,输出访问日志
//			RequestLogHandler _log = new RequestLogHandler();
//			_log.setRequestLog(createRequestLog());
//			_result.setHandlers(new Handler[] { _contexts, _log });
//		} else {
//			_result.setHandlers(new Handler[] { _contexts });
//		}
		return _ctx;
	}

	private RequestLog createRequestLog() {
		NCSARequestLog _log = new NCSARequestLog();

		File _logPath = new File(config.logpath);
		_logPath.getParentFile().mkdirs();
		_log.setFilename(_logPath.getPath());
		_log.setRetainDays(7);
		_log.setExtended(false);
		_log.setAppend(true);
		_log.setLogTimeZone("GMT");
		_log.setLogLatency(true);
		return _log;
	}

	// ---------------------------
	// Discover the war path
	// ---------------------------

	protected boolean isRunningInShadedJar() {
		try {
			Class.forName(config.scanclass);
			return false;
		} catch (ClassNotFoundException anExc) {
			return true;
		}
	}

	public URL getResource(String aResource) {
		return Thread.currentThread().getContextClassLoader().getResource(aResource);
	}

	private String getShadedWarUrl() {
		String _urlStr = getResource(config.web_xml).toString();
		// Strip off "WEB-INF/web.xml"
		System.out.println("[AbstractServer.getShadedWarUrl]:url=" + _urlStr);
		return _urlStr.substring(0, _urlStr.length() - 15);
	}
}
